package com.lu.system.Interceptor;

import com.lu.common.utils.TokenUtils;
import io.jsonwebtoken.Claims;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("LoginInterceptor---preHandle");
        if (request.getRequestURI().toString().equals("/systemLogin/login")
                || request.getRequestURI().toString().equals("/systemLogin/toLoginMsg")
                || request.getRequestURI().toString().equals("/index")) {
            return true;
        }
        String assess_token = request.getParameter("access_token");
        if (!StringUtils.isEmpty(assess_token)) {
            try {
                Claims claims = TokenUtils.parseJWT(assess_token);
                return true;
            } catch (Exception e) {
                //token失效
                request.getRequestDispatcher("/systemLogin/toLoginMsg").forward(request, response);
            }
        } else {
            request.getRequestDispatcher("/systemLogin/toLoginMsg").forward(request, response);
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        System.out.println("LoginInterceptor---postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        System.out.println("LoginInterceptor---afterCompletion");
    }
}
